package com.saxon.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

public class DownLoading extends HttpServlet {
    @Override
    protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.确定位置和名字
        String location = "D:\\IDEAL项目\\Saxon_01_servlet\\Saxon_Servlet_son_respond\\src\\main\\resources\\1.png";
        String filename = location.substring (location.lastIndexOf ("\\") + 1);
        //2.设置传输的头文件
        resp.setHeader ("Content-Disposition", "attachment; filename=" + filename);
        //3.建立缓冲区
        int len = 0;
        byte[] buffer = new byte[1024];
        //4.将下载文件变成输入流
        FileInputStream in = new FileInputStream (location);
        //5.获得输出流是，下载
        ServletOutputStream out = resp.getOutputStream ();
        //in.read (buffer) 将文件读取到缓存中
        while (in.read (buffer) != - 1) {
            out.write (buffer, 0, len);//将这个缓存给客户端，响应
        }
        out.close ();
        in.close ();
    }

    @Override
    protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet (req, resp);
    }
}
